package com.sunyur.tailor.channel.web.outer.org.controller;

import com.alibaba.fastjson.JSON;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.base.ValidList;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.service.inner.org.param.OrgSyncInfoParam;
import com.sunyur.tailor.channel.service.inner.org.service.SunyurOrgService;
import com.sunyur.tailor.channel.web.outer.org.dto.OrgSyncInfoDTO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author pengbing
 * @Description //组织数据控制层
 * @Date 15:45 2021/6/1
 * @Param
 * @return
 **/
@Log4j2
@RestController
@RequestMapping("/outer/org")
public class OrgController {
    /**
     * 组织服务
     */
    @Autowired
    private SunyurOrgService sunyurOrgService;

    /**
     * 同步创建组织
     */
    @PostMapping(value = "/batchCreate", produces = MediaType.APPLICATION_JSON_VALUE)
    public ChannelResult batchCreate(@RequestBody @Valid ValidList<OrgSyncInfoDTO> orgSyncInfoDTOS) {
        log.info("OrgController batchCreate param:{}", JSON.toJSONString(orgSyncInfoDTOS));
        ChannelResult result = new ChannelResult<>();
        if (CollectionUtils.isEmpty(orgSyncInfoDTOS)) {
            log.error("OrgController batchCreate param is null");
            result.setError(MiddleResultEnum.PARAM_NULL.getCode(), MiddleResultEnum.PARAM_NULL.getValue());
            return result;
        }
        try {
            List<OrgSyncInfoParam> orgSyncInfoParamList = getOrgSyncInfoParams(orgSyncInfoDTOS);
            result = sunyurOrgService.syncOrgList(orgSyncInfoParamList);
        } catch (Exception e) {
            log.error("OrgController batchCreate exception:{}", e);
            result.setError(MiddleResultEnum.EXCEPTION.getCode(), MiddleResultEnum.EXCEPTION.getValue());
        }
        return result;
    }

    private List<OrgSyncInfoParam> getOrgSyncInfoParams(List<OrgSyncInfoDTO> orgSyncInfoDTOS) {
        List<OrgSyncInfoParam> orgSyncInfoParamList=new ArrayList<>();
        orgSyncInfoDTOS.forEach(items -> {
            OrgSyncInfoParam target = new OrgSyncInfoParam();
            BeanUtils.copyProperties(items, target);
            orgSyncInfoParamList.add(target);
        });
        return orgSyncInfoParamList;
    }
}